package com.xzh.wms.mybatisx;


import cn.hutool.core.util.ObjectUtil;
import cn.xzh.smart.core.util.UserSessionContext;
import com.xzh.wms.entity.BaseEntity;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;

@Component
@Intercepts({
        @Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class})
})
public class ParameterPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        ParameterHandler parameterHandler=(ParameterHandler)invocation.getTarget();
        Object object = parameterHandler.getParameterObject();
//        方法一：//通过反射查看lastUpdateBy字段是否存在
//        Field field = ReflectUtil.getField(object.getClass(), "listUpdateBy");
//        if (ObjectUtil.isNotEmpty(field)){
//            String nickName = UserSessionContext.get().getNickName();
//            ReflectUtil.setFieldValue(object.getClass(),field,nickName);
//        }
        if (object instanceof BaseEntity && ObjectUtil.isNotEmpty(UserSessionContext.get())){
            BaseEntity baseEntity=(BaseEntity) object;
            String nickName = UserSessionContext.get().getNickName();
            baseEntity.setLastUpdateBy(nickName);
        }
        return invocation.proceed();
    }
}
